package com.bo.interceptor;

import com.bo.pojo.Result;
import com.bo.utils.JwtUtils;
import com.google.gson.JsonObject;
import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import netscape.javascript.JSObject;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author huangbo
 * @version 1.0.0
 */
@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override   //目标资源运行前执行，带boolean返回值 true-放行  false-不放行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle=======");
        //获取请求url
        String url = request.getRequestURL().toString();
        log.info("请求的url: {}",url);

        //判断请求url中是否包含login，如果包含则执行登录操作，放行
        if(url.contains("login")){
            log.info("放行=====");
            return true;
        }

        //获取请求头中的token
        String jwt = request.getHeader("token");

        //判断token是否存在
        if(!StringUtils.hasLength(jwt)){
            log.info("请求token为空，返回未登录的信息");
            Result err = Result.error("NOT_LOGIN");
            //手动转换 对象json -> 阿里巴巴fastJSON
            String notLogin = JSONObject.toJSONString(err);
            response.getWriter().write(notLogin);
            return false;
        }

        //解析token
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析令牌失败，返回为登录的信息");
            Result err = Result.error("NOT_LOGIN");
            String notLogin = JSONObject.toJSONString(err);
            response.getWriter().write(notLogin);
            return false;
        }

        //如果都没问题，放行
        log.info("令牌存在且合法，放行");
        return true;
    }

    @Override   //目标资源方法运行后运行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle======");
//        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override   //视图渲染完毕后运行，最后预想
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion=======");
//        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
